import React, { useState, useEffect } from 'react';
import AddContactForm from './components/AddContactForm';
import EditContactForm from './components/EditContactForm';
import ContactList from './components/ContactList';

function App() {
    const [contacts, setContacts] = useState([]);
    const [editingContact, setEditingContact] = useState(null);

    useEffect(() => {
        fetch('/contacts')
            .then(response => response.json())
            .then(data => setContacts(data));
    }, []);

    const addContact = (contact) => {
        fetch('/contacts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(contact)
        }).then(() => {
            setContacts([...contacts, contact]);
        });
    };

    const editContact = (contact) => {
        fetch(`/contacts/${contact.name}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(contact)
        }).then(() => {
            setContacts(contacts.map(c => (c.name === contact.name ? contact : c)));
        });
    };

    const deleteContact = (name) => {
        fetch(`/contacts/${name}`, {
            method: 'DELETE'
        }).then(() => {
            setContacts(contacts.filter(c => c.name !== name));
        });
    };

    return (
        <div>
            <h1>个人通讯录</h1>
            <AddContactForm onAdd={addContact} />
            {editingContact && <EditContactForm contact={editingContact} onSave={editContact} />}
            <ContactList contacts={contacts} onEdit={setEditingContact} onDelete={deleteContact} />
        </div>
    );
}

export default App;
